/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package websom;

import domain.NewsArticle;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

/**
 *
 * @author Teddy
 */
public class Parser extends DefaultHandler implements Runnable {

    private String attr = "";
    private String tag = "";
    private String tmp = "";
    private NewsArticle newsArticle = new NewsArticle();
    private String codesClass = "";
    private String path;
    private ParserController controller;

    public Parser(String folder,String fileToParse,ParserController controller) {
        this.path = folder + "\\" + fileToParse;
        this.controller = controller;
        newsArticle.setFileName(fileToParse);
    }

    private void parseXmlFile(String filePath) {
        //get a factory
        SAXParserFactory spf = SAXParserFactory.newInstance();
        try {

            //get a new instance of parser
            SAXParser sp = spf.newSAXParser();

            //parse the file and also register this class for call backs
            sp.parse(filePath, this);


        } catch (SAXException se) {
            se.printStackTrace();
        } catch (ParserConfigurationException pce) {
            pce.printStackTrace();
        } catch (IOException ie) {
            ie.printStackTrace();
        }
    }

    @Override
    public void startElement(String uri, String localName, String qName, org.xml.sax.Attributes attributes) throws SAXException {
        if (qName.equalsIgnoreCase("newsitem")) {
            newsArticle.setItemId(Long.parseLong(attributes.getValue("itemid")));
            newsArticle.setDate(attributes.getValue("date"));
            newsArticle.setId(attributes.getValue("id"));
        } else if (qName.equals("title") || qName.equals("text")) {
            attr = qName;
            tmp = "";
        } else if (qName.equalsIgnoreCase("codes")) {
            codesClass = attributes.getValue("class");
        } else if (qName.equalsIgnoreCase("code")) {
            if (codesClass.equalsIgnoreCase("bip:countries:1.0")) {
                newsArticle.getRegionCode().add(attributes.getValue("code"));
            } else if (codesClass.equalsIgnoreCase("bip:industries:1.0")) {
                newsArticle.getIndustryCode().add(attributes.getValue("code"));
            } else if (codesClass.equalsIgnoreCase("bip:topics:1.0")) {
                newsArticle.getTopicCode().add(attributes.getValue("code"));
            }
        } else if (qName.equalsIgnoreCase("dc")) {
            if (attributes.getValue("element").equalsIgnoreCase("dc.date.created")) {
                try {
                    DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
                    Date date = (Date) formatter.parse(attributes.getValue("value"));
                    newsArticle.setDateCreated(date);
                } catch (ParseException ex) {
                    Logger.getLogger(Parser.class.getName()).log(Level.SEVERE, null, ex);
                }
            } else if (attributes.getValue("element").equalsIgnoreCase("dc.publisher")) {

                newsArticle.setPublisher(attributes.getValue("value"));

            } else if (attributes.getValue("element").equalsIgnoreCase("dc.date.published")) {
                try {
                    DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
                    Date date = (Date) formatter.parse(attributes.getValue("value"));
                    newsArticle.setDatePublished(date);
                } catch (ParseException ex) {
                    Logger.getLogger(Parser.class.getName()).log(Level.SEVERE, null, ex);
                }
            } else if (attributes.getValue("element").equalsIgnoreCase("dc.source")) {

                newsArticle.setSource(attributes.getValue("value"));

            }
        }
        tag = qName;
    }

    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
        if (attr.equals("title")) {
            tmp += new String(ch, start, length).trim() + " ";
            newsArticle.setTitle(tmp.trim());
        } else if (attr.equals("text")) {
            tmp += new String(ch, start, length).trim() + " ";
            newsArticle.setText(tmp.trim());
        } else if (tag.equalsIgnoreCase("headline")) {
            newsArticle.setHeadline(new String(ch, start, length).trim());
        } else if (tag.equalsIgnoreCase("dateline")) {
            newsArticle.setDateLine(new String(ch, start, length).trim());
        } else if (tag.equalsIgnoreCase("copyright")) {
            newsArticle.setCopyright(new String(ch, start, length).trim());
        }
    }

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
        if (attr.equals("title") || qName.equals("text")) {
            attr = "";
            tmp = "";
        } else if (attr.equalsIgnoreCase("codes")) {
            codesClass = "";
        }
        tag = "";
    }

    public NewsArticle getNewsArticle() {
        return newsArticle;
    }

    public void run() {
       parseXmlFile(path);

        /*for (Field field : NewsArticle.class.getFields()) {
            try {
                System.out.println(field.getName() + " ------------ " + field.get(newsArticle));
            } catch (IllegalArgumentException ex) {
                Logger.getLogger(Parser.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                Logger.getLogger(Parser.class.getName()).log(Level.SEVERE, null, ex);
            }
        }*/
        controller.addNewsArticle(newsArticle);
    }

}

